<?php
namespace App\Model;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class GrasslandSheep extends BaseModel
{
    protected $connection = 'api';
    protected $systemTable = 'system_config';
    protected $user_table = 'user';
    protected $diamondStream_table = 'finance_diamond_stream';
    protected $giftStream_table = 'gift_stream';
    protected $giftBag_table = 'gift_bag';

    protected $activityConn = 'activity';
    protected $lc_config_table = 'grasslandsheep_config';
    protected $lc_buygift_table = 'grasslandsheep_buygift';
    protected $lc_dayStat_table = 'grasslandsheep_day_statistics';
    protected $lc_trackpool_log_table = 'grasslandsheep_trackpool_log';
    protected $lc_event_v3_table = 'grasslandsheep_event_v3';
    protected $lc_stat_v3_table = 'grasslandsheep_statistics_v3';

    //对应倍率
    public $poolRateHash = [
        '1' => ['magn'=>2, 'rate'=>4910, 'name'=>'小白兔'],
        '2' => ['magn'=>4, 'rate'=>2480, 'name'=>'小狮子'],
        '3' => ['magn'=>7, 'rate'=>1410, 'name'=>'小熊熊'],
        '4' => ['magn'=>14, 'rate'=>700, 'name'=>'可爱猪'],
        '5' => ['magn'=>33, 'rate'=>300, 'name'=>'萌萌猫'],
        '6' => ['magn'=>99, 'rate'=>100, 'name'=>'卖萌牛'],
        '7' => ['magn'=>99, 'rate'=>100, 'name'=>'小企鹅'],
    ];

    //森林狩猎配置获取
    public function grasslandSheepGetConfig($params)
    {
        $res = curl_request(getKkaudioActivityUrl() . '/inner/grasslandSheep/getGrasslandSheepConfig', $params, 'urlencoded', 'GET');
        $res = curlResultHandle($res);
        if(!empty($res['data'])) {
            $res['data'] = array_column($res['data'], 'value', 'key');
        }
        return $res;
    }

    //森林狩猎配置修改
    public function grasslandSheepUpdateConfig($params)
    {
        $res = curl_request(getKkaudioActivityUrl() . '/inner/grasslandSheep/updateGrasslandSheepConfig', $params, 'urlencoded', 'POST');
        return curlResultHandle($res);
    }

    //森林狩猎配置修改
    public function grasslandSheepUpdateTrackpool($params, $user)
    {
        $params['admin_id'] = $user['id'];

        $res = curl_request(getKkaudioActivityUrl() . '/inner/grasslandSheep/updateGrasslandSheepTrackpool', $params, 'urlencoded', 'POST');
        return curlResultHandle($res);
    }

    //森林狩猎押注池修改记录列表
    public function grasslandSheepTrackpoolList(Request $request)
    {
        $limit = $request->input('limit', 10);
        $page = $request->input('page', 1);

        $query = DB::connection($this->activityConn)->table($this->lc_trackpool_log_table)->orderBy('id', 'desc');
        $result = $query->paginate($limit, ['*'], 'page', $page);
        $result = objToArray($result);

        return $result;
    }

    //全家总动员统计整体数据V3
    public function statSearchAllV3(Request $request)
    {
        $useGiftId = 472;
        // $useGiftPrice = 10;
        $useGiftPrice = 100;
        // $minPrice = 10;
        $minPrice = 100;
        $date_st = $request->input('date_st');
        $date_ed = $request->input('date_ed');
        if(empty($date_st) || empty($date_ed)) {
            return [
                'code' => 50000,
                'msg' => '日期必须选择',
                'data' => [],
            ];
        }
        $time_st = date("Y-m-d H:i:s", strtotime($date_st));
        $time_ed = date("Y-m-d H:i:s", strtotime($date_ed));

        $info_1 = DB::connection($this->activityConn)->table($this->lc_stat_v3_table)
            ->selectRaw('sum(stakeNumAll) as stakeNumAll, sum(stakeNum) as stakeNum, sum(stakePriceAll) as stakePriceAll, sum(rewardPriceAll) as rewardPriceAll, sum(porfitPoolAll) as porfitPoolAll, sum(porfitPoolDecr) as porfitPoolDecr')
            ->where('created_at', '>=', $time_st)
            ->where('created_at', '<=', $time_ed)
            ->first();
        $info_1 = objToArray($info_1);

        $userNum = DB::connection($this->activityConn)->table($this->lc_event_v3_table)
            ->selectRaw('count(DISTINCT user_id) as userNum')
            ->where('created_at', '>=', $time_st)
            ->where('created_at', '<=', $time_ed)
            ->where('is_delete', 0)
            ->first();
        $userNum = objToArray($userNum);

        $info_2 = DB::connection($this->activityConn)->table($this->lc_event_v3_table)
            ->selectRaw('poolId,count(1) as stakeNumAll,sum(basePrice) as stakePriceAll')
            ->where('created_at', '>=', $time_st)
            ->where('created_at', '<=', $time_ed)
            ->where('is_delete', 0)
            ->groupBy('poolId')
            ->get();
        $info_2 = array_column(objToArray($info_2), null, 'poolId');

        $info_3 = DB::connection($this->activityConn)->table($this->lc_event_v3_table)
            ->selectRaw('poolId,sum(rewardPrice) as rewardNum')
            ->where('created_at', '>=', $time_st)
            ->where('created_at', '<=', $time_ed)
            ->where('status', 1)
            ->where('is_delete', 0)
            ->groupBy('poolId')
            ->get();
        $info_3 = array_column(objToArray($info_3), 'rewardNum', 'poolId');

        $data = [];
        //参与人数
        $data['userNum'] = (int) $userNum['userNum'];
        //押注次数
        $data['stakeNumAll'] = (int) $info_1['stakeNumAll'];
        //押中次数
        $data['stakeNum'] = (int) $info_1['stakeNum'];
        //下注券数
        $data['stakePriceNum'] = (int) $info_1['stakePriceAll'];
        //消耗钻石数量
        $data['stakePriceAll'] = $info_1['stakePriceAll']*$minPrice;
        //产出礼物数量
        $data['rewardNumAll'] = $info_1['rewardPriceAll'];
        //产出礼物价值钻石数量
        $data['rewardPriceAll'] = $info_1['rewardPriceAll']*$useGiftPrice;
        //抽水数量(礼物) 利润池新增(预计)-利润池新增扣除
        $data['porfitNum'] = ($info_1['porfitPoolAll'] - $info_1['porfitPoolDecr']);
        //抽水数量(钻石) 抽水券数*捕羊券礼物价值
        $data['porfitPriceNum'] = $data['porfitNum']*$minPrice;
        //利润数量(钻石) 消耗数量-产出数量
        $data['porfitNum2'] = $data['stakePriceAll'] - $data['rewardPriceAll'];
        //利润率 利润/消耗
        $data['porfitRate'] = (empty($data['stakePriceAll']) ? 0 : round($data['porfitNum2']/$data['stakePriceAll'], 2)*100).'%';
        //返奖率    产出/消耗
        $data['returnRate'] = (empty($data['stakePriceAll']) ? 0 : round($data['rewardPriceAll']/$data['stakePriceAll'], 2)*100).'%';
        //赛道详情
        $data['poolList'] = [];
        foreach($this->poolRateHash as $poolId=>$val) {
            $item = [];
            $item['poolId'] = $poolId;
            $item['name'] = $val['name'];
            //押注次数
            $item['stakeNumAll'] = empty($info_2[$poolId]['stakeNumAll']) ? 0 : intval($info_2[$poolId]['stakeNumAll']);
            //下注券数
            $item['stakePriceNum'] = empty($info_2[$poolId]['stakePriceAll']) ? 0 : intval($info_2[$poolId]['stakePriceAll']);
            //消耗数量(钻石)
            $item['stakePriceAll'] = $item['stakePriceNum']*$minPrice;
            //产出数量(礼物)
            $item['rewardNumAll'] = empty($info_3[$poolId]) ? 0 : $info_3[$poolId];
            //产出数量(钻石)
            $item['rewardPriceAll'] = $item['rewardNumAll']*$useGiftPrice;
            //返奖率    产出/消耗
            $item['returnRate'] = (empty($item['stakePriceAll']) ? 0 : round($item['rewardPriceAll']/$item['stakePriceAll'], 2)*100).'%';

            $data['poolList'][] = $item;
        }

        return [
            'code' => 20000,
            'msg' => '成功',
            'data' => $data,
        ];
    }

    //森林狩猎单期数据V3
    public function statGameEveryV3(Request $request)
    {
        $useGiftId = 472;
        // $useGiftPrice = 10;
        $useGiftPrice = 100;
        // $minPrice = 10;
        $minPrice = 100;
        $limit = $request->input('limit', 10);
        $page = $request->input('page', 1);
        $date_st = $request->input('date_st');
        $date_ed = $request->input('date_ed');

        $query = DB::connection($this->activityConn)->table($this->lc_stat_v3_table)->orderBy('id', 'desc');
        if(!empty($date_st)) {
            $time_st = date("Y-m-d H:i:s", strtotime($date_st));
            $query = $query->where('created_at', '>=', $time_st);
        }
        if(!empty($date_ed)) {
            $time_ed = date("Y-m-d H:i:s", strtotime($date_ed));
            $query = $query->where('created_at', '<=', $time_ed);
        }

        $result = $query->paginate($limit, ['*'], 'page', $page);
        $result = objToArray($result);
        foreach($result['data'] as $key=>$val) {
            //下注券数
            $val['stakePriceNum'] = (int) $val['stakePriceAll'];
            //消耗数量(钻石)
            $val['stakePriceAll'] = $val['stakePriceAll']*$minPrice;
            //产出礼物数量
            $val['rewardNumAll'] = $val['rewardPriceAll'];
            //产出礼物价值钻石数量
            $val['rewardPriceAll'] = $val['rewardPriceAll']*$useGiftPrice;
            //抽水数量(礼物) 利润池新增(预计)-利润池新增扣除
            $val['porfitNum'] = $val['porfitPoolAll'] - $val['porfitPoolDecr'];
            //抽水数量(钻石) 抽水券数*捕羊券礼物价值
            $val['porfitPriceNum'] = $val['porfitNum']*$minPrice;
            //利润数量(钻石) 消耗-产出
            $val['porfitNum2'] = $val['stakePriceAll'] - $val['rewardPriceAll'];
            //利润率 利润/消耗
            $val['porfitRate'] = (empty($val['stakePriceAll']) ? 0 : round($val['porfitNum2']/$val['stakePriceAll'], 2)*100).'%';

            $result['data'][$key] = $val;
        }

        return $result;
    }

    //森林狩猎用户参与明细V3
    public function statUserInfoV3(Request $request)
    {
        $useGiftId = 472;
        // $useGiftPrice = 10;
        $useGiftPrice = 100;
        // $minPrice = 10;
        $minPrice = 100;
        $date_st = $request->input('date_st');
        $date_ed = $request->input('date_ed');
        $user_id = $request->input('user_id');
        $uuid = $request->input('uuid');
        if(empty($date_st) || empty($date_ed)) {
            return [
                'code' => 50000,
                'msg' => '日期必须选择',
                'data' => [],
            ];
        }
        $result = ['list'=>[], 'total'=>0];

        $time_st = date("Y-m-d H:i:s", strtotime($date_st));
        $time_ed = date("Y-m-d H:i:s", strtotime($date_ed));

        $userIds = [];
        //获取日期内的参与过的用户
        if(empty($user_id) && empty($uuid)) {
            $userIds = DB::connection($this->activityConn)->table($this->lc_event_v3_table)
                ->where('created_at', '>=', $time_st)
                ->where('created_at', '<=', $time_ed)
                ->distinct()
                ->pluck('user_id');
            $userIds = objToArray($userIds);
        }else{
            if(!empty($user_id)) {
                $userInfo = DB::connection($this->connection)->table($this->user_table)->where('user_id', $user_id)->first();
            }
            if(!empty($uuid)) {
                $userInfo = DB::connection($this->connection)->table($this->user_table)->where('uuid', $uuid)->first();
            }
            if(empty($userInfo)) {
                return [
                    'code' => 50000,
                    'msg' => '搜索用户不存在',
                    'data' => [],
                ];
            }
            $userInfo = objToArray($userInfo);
            $userIds = [$userInfo['user_id']];
        }
        $result['total'] = count($userIds);
        if(empty($userIds)) {
            return [
                'code' => 20000,
                'msg' => '成功',
                'data' => $result,
            ];
        }

        sort($userIds);
        //获取用户信息
        $userList = DB::connection($this->connection)->table($this->user_table)->select('user_id','uuid','nickname')->whereIn('user_id', $userIds)->get();
        $userList = objToArray($userList);

        $info_1 = DB::connection($this->activityConn)->table($this->lc_event_v3_table)
            ->selectRaw('user_id, count(DISTINCT gameNum) as joinNum, count(1) as stakeNumAll, sum(basePrice) as stakePriceAll')
            ->where('created_at', '>=', $time_st)
            ->where('created_at', '<=', $time_ed)
            ->whereIn('user_id', $userIds)
            ->where('is_delete', 0)
            ->groupBy('user_id')
            ->get();
        $info_1 = objToArray($info_1);
        $info_1 = array_column($info_1, null, 'user_id');

        $info_2 = DB::connection($this->activityConn)->table($this->lc_event_v3_table)
            ->selectRaw('user_id, count(1) as stakeNum, sum(rewardPrice) as rewardPriceAll')
            ->where('created_at', '>=', $time_st)
            ->where('created_at', '<=', $time_ed)
            ->where('status', 1)
            ->whereIn('user_id', $userIds)
            ->where('is_delete', 0)
            ->groupBy('user_id')
            ->get();
        $info_2 = objToArray($info_2);
        $info_2 = array_column($info_2, null, 'user_id');

        foreach($userList as $val) {
            $data = [];
            //用户ID
            $data['userId'] = $val['user_id'];
            //用户uuid
            $data['uuid'] = $val['uuid'];
            //用户昵称
            $data['nickname'] = $val['nickname'];
            //参与次数
            $data['joinNum'] = empty($info_1[$val['user_id']]['joinNum']) ? 0 : $info_1[$val['user_id']]['joinNum'];
            //押注次数
            $data['stakeNumAll'] = empty($info_1[$val['user_id']]['stakeNumAll']) ? 0 : $info_1[$val['user_id']]['stakeNumAll'];
            //押中次数
            $data['stakeNum'] = empty($info_2[$val['user_id']]['stakeNum']) ? 0 : $info_2[$val['user_id']]['stakeNum'];
            //下注券数
            $data['stakePriceNum'] = empty($info_1[$val['user_id']]['stakePriceAll']) ? 0 : intval($info_1[$val['user_id']]['stakePriceAll']);
            //消耗钻石数量
            $data['stakePriceAll'] = $data['stakePriceNum']*$minPrice;
            //产出礼物数量
            $data['rewardNumAll'] = empty($info_2[$val['user_id']]['rewardPriceAll']) ? 0 : intval($info_2[$val['user_id']]['rewardPriceAll']);
            //产出钻石数量
            $data['rewardPriceAll'] = $data['rewardNumAll']*$useGiftPrice;
            //利润钻石数量 产出-消耗
            $data['porfitNum'] =  $data['rewardPriceAll'] - $data['stakePriceAll'];
            //利润率 利润/消耗
            $data['porfitRate'] = (empty($data['stakePriceAll']) ? 0 : round($data['porfitNum']/$data['stakePriceAll'], 2)*100).'%';

            $result['list'][] = $data;
        }

        return [
            'code' => 20000,
            'msg' => '成功',
            'data' => $result,
        ];
    }

}
